/*
 * DA3.c
 *
 * Created: 3/11/2014 10:33:14 AM
 *  Author: hillm3
 */ 
// http://www.youtube.com/watch?v=KDIMobO62Rk -> youtube video demonstration.

#include <avr/io.h>
#include <avr/interrupt.h>

int every16 = 0;


ISR(TIMER1_OVF_vect){
	// This happens every 10 cycles.
	// From main() and which the wire connects from PD2(Int0) to PD6. PD6 outputs every 10 cycles.
			PORTD ^= 1<<7; // Change the output bit so timer1 can recieve the change in signal. NOTE: This is external
	every16++; // Increment the global counter
	if(every16==32){ // Once it hits 32, because TIMER1 overflow has a rising and a falling, and I am only measuring the falling, so I need twice the amount of interrupt checks
		PORTD ^= 1<<6; 		// Output 9th bit of LED bar
		every16=0; // Clear the counter
	}

PORTB = TCNT0; // Set timer0 clock to PORTB. This only changes every other TIMER1 overflow, due to it only on falling.
}



int main(void)
{
	
		DDRB = 0b11111111;///Sets the direction Used for LED bits 0-7
		DDRD = 0b11000000;///Sets the direction. We use bit 6 and 7 of port D. bit 6 is every 10 cycles, bit 7 is every 40 cycles. Bit 2 is the interrupt reader
		PORTB = 0b00000000; // Set PORTB to 0 initially.
		PORTD = 0b00000000; // Set PORTD to 0 initially.
		TCCR1A = 0b00000000;// Make sure it is 0 initially
		TCCR1B = 0b00000010; 	// cs is 010 for clk prescalar of 8, That way each overflow is 8*65536/8M = 1/16th of a second.
		TCCR0B = 0b00000110;// Reads an external clock on the falling edge. NOTE: This is from PORTD7 connected to PORTD4.
	
				EICRA = 0b00000010; // Sets the interrupt for falling edge.
				TIMSK1 = 1; // Enables the overflow interrupt.
				sei(); // Enable the interrupt
	


	
    while(1)
    {
		/// Just waiting for interrupt.
    }
}
